package com.lixi.spider;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lixi.entity.Bat;
import com.lixi.service.BatService;
import com.lixi.service.Impl.BatServiceImpl;
import org.jsoup.Jsoup;

import java.io.IOException;

import org.jsoup.nodes.Document;

/**
 * @author lixi
 * @create 2020-02-15:17:44
 */
public class Load {
    private Document doc;
    private String url = "";
    private JSONArray Citys;
    private String CityName;
    private BatService batService;

    //构造方法 加载url什么的
    public Load(String url) throws IOException {
        this.url = url;
        doc = Jsoup.connect(url).get();
        batService = new BatServiceImpl();
    }
    //拿到指定省份的城市
    public void jsonLoad(String CityName) {
        this.CityName = CityName;
        String json = doc.body().select("script[id=getAreaStat]").html();
        //还好我发现了他的操作方式
        int Right = 0;
        int Left = 0;
        //把两边的JS代码删除
        for (int i = 0, j = json.length() - 1; ; i++, j--) {
            if (json.charAt(i) == '[' && Right == 0) {
                Right = --i;
            }
            if (json.charAt(j) == ']' && Left == 0) {
                Left = ++j;
            }
            if (Left != 0 && Right != 0) {
                break;
            }
        }
        json = json.substring(Right);
        json = json.substring(0, Left - Right);
        JSONArray arrays = JSON.parseArray(json);
        for (Object array : arrays) {
            if (((JSONObject) array).get("provinceName").equals(CityName)) {
                JSONObject node = ((JSONObject) array);
                this.Citys = JSON.parseArray(node.get("cities").toString());
            }
        }
    }
    //类型转换
    private Bat JsonToBat(JSONObject node) {
        Bat bat = new Bat();
        bat.setName(node.get("cityName").toString());
        bat.setNow(Integer.parseInt(node.get("currentConfirmedCount").toString()));
        bat.setDie(Integer.parseInt(node.get("deadCount").toString()));
        bat.setCure(Integer.parseInt(node.get("curedCount").toString()));
        bat.setCount(Integer.parseInt(node.get("confirmedCount").toString()));
        return bat;
    }
    /*第一次添加就用这个*/
    public void addToMysql() {
        for (Object city : Citys) {
            JSONObject node = (JSONObject) city;
            batService.addBat(JsonToBat(node));
        }
    }
    //看名字就知道
    public void updToMysql() {
        System.out.println("更新一次");
        for (Object city : Citys) {
            JSONObject node = (JSONObject) city;
            batService.updBat(JsonToBat(node));
        }
    }
}
